package com.example.demo.auth;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.Redis.RedisUtil;
import com.example.demo.common.AccessResult;
import com.example.demo.common.CommonConstants;
import com.example.demo.common.RedisConstants;
import com.example.demo.util.HttpClientUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Set;

@Service
public class AuthService {

    @Resource
    private RedisUtil redisUtil;

    @Value("${CalculateAddr}")
    private String calculateAddr;

    @Value("${EvaluateAddr}")
    private String evaluateAddr;

    public JSONObject auth(JSONObject identity, String serviceName){
        JSONObject jsonObject = new JSONObject();

        Set subSet = (Set) redisUtil.hget(RedisConstants.policy_prefix+serviceName,RedisConstants.subject);
        JSONObject json = JSONObject.parseObject(identity.toString());

        if(! subSet.contains(identity.get("ROLE"))){
            evaluate(json,"permission denied");
            setJson(jsonObject,false, AccessResult.PERMISSION_DENIED);
            return jsonObject;
        }

        String trustRes = HttpClientUtil.doPostWithBody(calculateAddr,identity.toJSONString());
        int curTrust = Integer.parseInt(trustRes);

        int ultTrust = (int) redisUtil.hget(RedisConstants.policy_prefix+serviceName,RedisConstants.trust);
        if(curTrust >= ultTrust){
            evaluate(json,"success");
            setJson(jsonObject,true, AccessResult.SUCCESS);
            return jsonObject;
        }

        evaluate(json,"trust not enough");
        setJson(jsonObject,false, AccessResult.LOW_TRUST);
        return jsonObject;
    }

    private void evaluate(JSONObject js, String reqRes){
        js.put("reqResult",reqRes);
        HttpClientUtil.doPostWithBody(evaluateAddr,js.toJSONString());
    }

    private void setJson(JSONObject jsonObject, boolean res, String res_message){
        jsonObject.put(CommonConstants.RES,res);
        jsonObject.put(CommonConstants.RES_MESSAGE,res_message);
    }
}
